package com.snap.vseries.ui.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.SweepGradient;
import android.util.AttributeSet;
import android.view.View;

import com.snap.vseries.R;

import java.util.Locale;

import me.jessyan.autosize.utils.AutoSizeUtils;


/**
 * @author Rachel
 */
public class DashboardProgressView extends View {
    /**
     * 为画布设置抗锯齿
     */
    private PaintFlagsDrawFilter mDrawFilter;
    /**
     * 时刻笔触大小
     */
    private float mScaleStrokeWidth;
    /**
     * 时刻笔触大小
     */
    private float mMaxScaleStrokeWidth;
    /**
     * 普通时刻长度
     */
    private float mScaleLineWidth;
    /**
     * 整10时刻长度-普通时刻长度
     */
    private float mPadding;
    /**
     * 宽度
     */
    private int width;
    /**
     * 当前温度
     */
    private String temperature = "";
    /**
     * 阶段进度
     */
    private String sectionProgress = "0/0";
    /**
     * 时间进度
     */
    private float timeProgress;
    private int ringPadding;
    /**
     * 通用画笔
     */
    private Paint mPaint;
    private Paint mRingPaint;
    private float mTextSize;
    private int mTextColor;
    private int ringStroke;
    private RectF oval;


    public DashboardProgressView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public DashboardProgressView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // 获取属性
        obtainStyledAttrs(attrs);
        //初始化属性
        initAttrs();
        //初始化画笔
        initPaint();
        // 为画布实现抗锯齿（边缘柔化）
        mDrawFilter = new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
    }

    public DashboardProgressView(Context context) {
        super(context);
    }

    private void obtainStyledAttrs(AttributeSet attrs) {
        TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.DashboardProgressView);
        mScaleLineWidth = typedArray.getDimension(R.styleable.DashboardProgressView_scaleLineWidth, AutoSizeUtils.dp2px(getContext(), 12));
        mScaleStrokeWidth = typedArray.getDimension(R.styleable.DashboardProgressView_scaleStrokeWidth, AutoSizeUtils.dp2px(getContext(), 1));
        mMaxScaleStrokeWidth = typedArray.getDimension(R.styleable.DashboardProgressView_scaleStrokeWidth, AutoSizeUtils.dp2px(getContext(), 2));
        mPadding = typedArray.getDimension(R.styleable.DashboardProgressView_padding, AutoSizeUtils.dp2px(getContext(), 6));
        //文字大小
        mTextSize = typedArray.getDimension(R.styleable.DashboardProgressView_textSize, AutoSizeUtils.sp2px(getContext(), 56));
        //文字
        mTextColor = typedArray.getColor(R.styleable.DashboardProgressView_textColor, 0xFF202023);
        // 一定要回收
        typedArray.recycle();
    }

    private void initAttrs() {
        ringStroke = AutoSizeUtils.dp2px(getContext(), 4);
        ringPadding = AutoSizeUtils.dp2px(getContext(), 60);
    }

    private void initPaint() {
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setDither(true);
        mRingPaint = new Paint();
        mRingPaint.setAntiAlias(true);
        mRingPaint.setDither(true);
        //设置画笔的画出的形状 笔帽
        mRingPaint.setStrokeCap(Paint.Cap.ROUND);
        mRingPaint.setStyle(Paint.Style.STROKE);
        mRingPaint.setStrokeWidth(ringStroke);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int i = measureWidthSize(widthMeasureSpec);
        int j = measureHeightSize(heightMeasureSpec);
        setMeasuredDimension(i, j);
    }


    /**
     * 测量宽高和屏幕作对比
     *
     * @param measureSpec 测量规格
     */
    private int measureWidthSize(int measureSpec) {
        int widthPixels = getResources().getDisplayMetrics().widthPixels;
        int size = MeasureSpec.getSize(measureSpec);
        width = Math.min(widthPixels, size);
        return width;
    }

    /**
     * 测量宽高和屏幕作对比
     *
     * @param measureSpec 测量规格
     */
    private int measureHeightSize(int measureSpec) {
        int heightPixels = getResources().getDisplayMetrics().heightPixels;
        int size = MeasureSpec.getSize(measureSpec);
        return Math.min(heightPixels, size);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //创建一个矩形
        // TODO: 2019/9/4 此处不应创建对象
        oval = new RectF(ringPadding, ringPadding, width - ringPadding, width - ringPadding);
        canvas.setDrawFilter(mDrawFilter);
        //绘制圆环
        drawCircleRing(canvas);
        // 绘制刻度尺
        printScale(canvas);
        //绘制文字
        drawText(canvas);
        //总进度数
        float totalAngle = 200;
        //尾部渲染度数
        float gradientAngleFooter = 15;
        //头部渲染度数
        float gradientAngleHeader = 15;
        //起始度数
        float startAngle = 170;
        //当前已经跨过的进度总数
        float sweepAngle = totalAngle * timeProgress / 100;
        //一半的宽度
        float half = width / 2f;
        int colorStart = 0xFF3866AB;
        int colorEnd = 0x003866AB;

        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(ringStroke);
        //蓝色
        mPaint.setColor(0xFF3866AB);
        //把整个进度条弧度分为四节：头部渲染块，实体块，端点，尾部渲染块
        if (sweepAngle <= gradientAngleHeader) {
            //进度小于15时，只绘制三节：头部渲染块（进度），端点，尾部渲染块
            gradientAngleHeader = sweepAngle;
        } else {
            //进度大于15时，绘制四节：头部渲染块（15），实体块（进度-15），端点，尾部渲染块
            canvas.drawArc(oval, startAngle + gradientAngleHeader, sweepAngle - gradientAngleHeader, false, mPaint);
        }
        //SweepGradient扫描/梯度渲染,取头部弧长进行颜色值渲染
        SweepGradient sweepGradientHeader1 = new SweepGradient(half, half, new int[]{colorEnd, colorStart}, new float[]{startAngle / 360, (startAngle + gradientAngleHeader) / 360});
        mRingPaint.setShader(sweepGradientHeader1);
        canvas.drawArc(oval, startAngle, gradientAngleHeader, false, mRingPaint);
        //旋转画布绘制端点及尾部
        canvas.rotate(sweepAngle, half, half);
        //端点
        float radius = half - ringPadding;
        float y = (float) (half + radius * Math.sin(10 * Math.PI / 180));
        float x = (float) (half - radius * Math.cos(10 * Math.PI / 180));
        canvas.drawCircle(x, y, ringStroke / 2f, mPaint);
        //渐变尾部
        float first = startAngle / 360;
        //剩余进度小于十五时，尾部渲染块=剩余进度
        if (sweepAngle >= (totalAngle - gradientAngleFooter)) {
            gradientAngleFooter = totalAngle - sweepAngle;
        }
        float second = (startAngle + gradientAngleFooter) / 360;
        //SweepGradient扫描/梯度渲染,尾部取弧长进行颜色值渲染
        SweepGradient sweepGradient = new SweepGradient(half, half, new int[]{colorStart, colorEnd}, new float[]{first, second});
        mRingPaint.setShader(sweepGradient);
        canvas.drawArc(oval, startAngle, startAngle + gradientAngleFooter, false, mRingPaint);
        //绘制完成再将画布旋转回来
        canvas.rotate(-sweepAngle, half, half);
    }


    public void setTemperature(float temperature) {
        this.temperature = String.format(Locale.CHINA, "%.2f", temperature);
    }

    /**
     * 设置运行状态,目前未使用到
     *
     * @param state 状态 运行中、已完成等
     */
    public void setState(String state) {
        String state1 = state;
    }

    /**
     * 显示循环段 几分之几
     *
     * @param sectionProgress 进度
     */
    public void setSectionProgress(String sectionProgress) {
        this.sectionProgress = sectionProgress;
    }


    /**
     * 显示总体进度
     *
     * @param timeProgress 已完成占总时间的比重
     */
    public void setTimeProgress(float timeProgress) {
        if (timeProgress > 100) {
            this.timeProgress = 100f;
        } else {
            this.timeProgress = timeProgress;
        }
    }

    /**
     * 绘制进度条
     *
     * @param canvas 画布
     */
    private void drawCircleRing(Canvas canvas) {
        //总进度数
        float totalAngle = 200;
        //尾部渲染度数
        float gradientAngleFooter = 15;
        //头部渲染度数
        float gradientAngleHeader = 15;
        //起始度数
        float startAngle = 170;
        //当前已经跨过的进度总数
        float sweepAngle = totalAngle * timeProgress / 100;
        //一半的宽度
        float half = width / 2f;
        int colorStart = 0xFF3866AB;
        int colorEnd = 0x003866AB;
        ringPadding = AutoSizeUtils.dp2px(getContext(), 60);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(ringStroke);
        //蓝色
        mPaint.setColor(0xFF3866AB);
        //创建一个矩形
        RectF oval = new RectF(ringPadding, ringPadding, width - ringPadding, width - ringPadding);
        //把整个进度条弧度分为四节：头部渲染块，实体块，端点，尾部渲染块
        if (sweepAngle <= gradientAngleHeader) {
            //进度小于15时，只绘制三节：头部渲染块（进度），端点，尾部渲染块
            gradientAngleHeader = sweepAngle;
        } else {
            //进度大于15时，绘制四节：头部渲染块（15），实体块（进度-15），端点，尾部渲染块
            canvas.drawArc(oval, startAngle + gradientAngleHeader, sweepAngle - gradientAngleHeader, false, mPaint);
        }
        //SweepGradient扫描/梯度渲染,取头部弧长进行颜色值渲染
        SweepGradient sweepGradientHeader1 = new SweepGradient(half, half, new int[]{colorEnd, colorStart}, new float[]{startAngle / 360, (startAngle + gradientAngleHeader) / 360});
        mRingPaint.setShader(sweepGradientHeader1);
        canvas.drawArc(oval, startAngle, gradientAngleHeader, false, mRingPaint);
        //旋转画布绘制端点及尾部
        canvas.rotate(sweepAngle, half, half);
        //端点
        float radius = half - ringPadding;
        float y = (float) (half + radius * Math.sin(10 * Math.PI / 180));
        float x = (float) (half - radius * Math.cos(10 * Math.PI / 180));
        canvas.drawCircle(x, y, ringStroke / 2f, mPaint);
        //渐变尾部
        float first = startAngle / 360f;
        //剩余进度小于十五时，尾部渲染块=剩余进度
        if (sweepAngle >= (totalAngle - gradientAngleFooter)) {
            gradientAngleFooter = totalAngle - sweepAngle;
        }
        float second = (startAngle + gradientAngleFooter) / 360f;
        //SweepGradient扫描/梯度渲染,尾部取弧长进行颜色值渲染
        SweepGradient sweepGradient = new SweepGradient(half, half, new int[]{colorStart, colorEnd}, new float[]{first, second});
        mRingPaint.setShader(sweepGradient);
        canvas.drawArc(oval, startAngle, startAngle + gradientAngleFooter, false, mRingPaint);
        //绘制完成再将画布旋转回来
        canvas.rotate(-sweepAngle, half, half);
    }

    private void drawText(Canvas canvas) {
        Paint cPaint = new Paint();
        cPaint.setAntiAlias(true);
        cPaint.setStyle(Paint.Style.FILL);
        cPaint.setTextSize(24);
        //黑色
        cPaint.setColor(0xFFC1C3CF);
        cPaint.setStrokeWidth(1.0f);

        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(1.0f);
        mPaint.setColor(0xFF8D909F);
        mPaint.setTextSize(AutoSizeUtils.sp2px(getContext(), 18));
        mPaint.setStyle(Paint.Style.FILL);
        //当前温度
        Rect textRect = new Rect();
        String tip = "当前温度";
        mPaint.getTextBounds(tip, 0, tip.length(), textRect);
        int tipHeight = ringPadding + AutoSizeUtils.dp2px(getContext(), 64);
        canvas.drawText(tip, width / 2f - textRect.width() / 2f, tipHeight, mPaint);
        //75C
        int padding = AutoSizeUtils.dp2px(getContext(), 16);
        mPaint.setColor(mTextColor);
        mPaint.setTextSize(mTextSize);
        Rect tempRect = new Rect();
        mPaint.getTextBounds(temperature, 0, temperature.length(), tempRect);
        int tempHeight = tipHeight + padding + tempRect.height();
        Rect cRect = new Rect();
        String text = "℃";
        cPaint.getTextBounds(text, 0, text.length(), cRect);

        Rect temp1Rect = new Rect();
        String temp = "88.88";
        mPaint.getTextBounds(temp, 0, temp.length(), temp1Rect);
        //绘制温度
        canvas.drawText(temperature, width / 2f - (temp1Rect.width() + cRect.width()) / 2f, tempHeight, mPaint);
        //绘制℃
        canvas.drawText(text, width / 2 - (temp1Rect.width() + cRect.width()) / 2 + temp1Rect.width() + AutoSizeUtils.dp2px(getContext(), 5),
                tipHeight + padding + cRect.height(), cPaint);
        //-
        mPaint.setColor(0xFFC1C3CF);
        int lineHeight = tempHeight + padding;
        canvas.drawLine(width / 2f - padding, lineHeight, width / 2f + padding, lineHeight, mPaint);
        //30/50循环
        mPaint.setColor(0xFF202023);
        mPaint.setTextSize(AutoSizeUtils.sp2px(getContext(), 24));
        Rect proRect = new Rect();
        mPaint.getTextBounds(sectionProgress, 0, sectionProgress.length(), proRect);
        int proHeight = lineHeight + padding + proRect.height();
        canvas.drawText(sectionProgress, width / 2f - proRect.width() / 2f, proHeight, mPaint);
    }

    /**
     * 绘制刻度尺
     *
     * @param canvas 画布
     */
    private void printScale(Canvas canvas) {
        mPaint.setColor(0xFFC1C3CF);
        mPaint.setStrokeWidth(mScaleStrokeWidth);
        //旋转画布至起始处
        canvas.rotate((float) -100, width / 2f, width / 2f);
        for (int i = 0; i <= 100; i = i + 2) {
            if (i % 10 == 0) {
                mPaint.setStyle(Paint.Style.STROKE);
                mPaint.setStrokeWidth(mMaxScaleStrokeWidth);
                canvas.drawLine(width / 2f, 0, width / 2f, mScaleLineWidth + mPadding, mPaint);
                //绘制刻度文字
                mPaint.setTextSize(AutoSizeUtils.sp2px(getContext(), 12));
                mPaint.setStrokeWidth(1.0f);
                mPaint.setStyle(Paint.Style.FILL);
                String text = i + "";
                Rect textBound = new Rect();
                mPaint.getTextBounds(text, 0, text.length(), textBound);
                canvas.drawText(text, width / 2f - textBound.width() / 2f, textBound.height() + AutoSizeUtils.dp2px(getContext(), 24), mPaint);
            } else {
                mPaint.setStyle(Paint.Style.STROKE);
                mPaint.setStrokeWidth(mScaleStrokeWidth);
                canvas.drawLine(width / 2f, mPadding, width / 2f, mPadding + mScaleLineWidth, mPaint);
            }
            //旋转51次
            canvas.rotate((float) 4, width / 2f, width / 2f);
        }
        //将画布旋转回来
        canvas.rotate((float) -104, width / 2f, width / 2f);
    }
}
